<?php


namespace app\Index\controller;

use library\Controller;
use think\Db;
use app\common\controller\MathCaptcha;

class User extends Controller
{
    //图形验证码
    public function getCaptcha()
    {
        try {
            $captcha = new MathCaptcha();
            $this->json($captcha->generate());
        } catch (\Exception $e) {
            $this->errors($e->getMessage());
        }
    }

    //登录
    public function login()
    {
        $data['username'] = $this->request->post('username') ?? '';
        $data['password'] = $this->request->post('password') ?? '';
        $code = $this->request->post('code') ?? '';
        $code_key = $this->request->post('code_key') ?? '';

        // 用户信息验证
        $map = ['is_deleted' => '0', 'username' => $data['username']];
        $user = Db::name('SystemUser')->where($map)->order('id desc')->find();
        if (empty($user)) $this->errors('登录账号或密码错误，请重新输入!');
        if (empty($user['status'])) $this->errors('账号已经被禁用，请联系管理员!');

        if ($code != $_SESSION[$code_key]) {
            $this->errors("验证码错误！");
        }

        if ($user['password'] !== md5($data['password'])) {
            sysoplogs('系统管理', "账号{$user['username']}登录密码错误，请注意账号安全！",$user['username']);
            $this->errors("登录账号或密码错误！");
        }

        $user['access_token'] = md5($user['id']);

        // 登录成功并更新账号
        Db::name('SystemUser')->where(['id' => $user['id']])->update([
            'login_at' => Db::raw('now()'), 'login_ip' => $this->request->ip(), 'access_token'=>$user['access_token'] ,'login_num' => Db::raw('login_num+1'),
        ]);

        sysoplogs('系统管理', '用户登录系统成功',$user['username']);
        $this->json($user);
    }

    //设置主题
    public function set_theme(){
        $data['id'] = $this->request->post('id') ?? '';
        $data['theme'] = $this->request->post('theme') ?? '';
        Db::name('SystemUser')->where(['id' => $data['id']])->update(['theme'=>$data['theme']]);
        $user = Db::name('SystemUser')->where(['id' => $data['id']])->order('id desc')->find();
        if($user){
            $time = time();
            $login_time = strtotime($user['login_at']);
            $difference = $time-$login_time;
            if($difference<86400){
                $user['access_token'] = md5($user['id']);
            }else{
                $user['access_token'] = '';
            }
        }
        $this->json($user);
    }

}